package com.yl.nettylearning.netty.day09;

import com.yl.nettylearning.netty.day08.StudentPOJO;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author yangl
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //读取从客户端发送的studentPOJO类型
        StudentInfo.MyMessage studentInfo = (StudentInfo.MyMessage) msg;
        if(studentInfo.getDataType() == StudentInfo.MyMessage.DataType.StudentType){
            System.out.println("客户端发送的数据是，id：" + studentInfo.getStudent().getId());
            System.out.println("姓名:" + studentInfo.getStudent().getName());
        }else if(studentInfo.getDataType() == StudentInfo.MyMessage.DataType.WorkerType){
            System.out.println("客户端发送的数据是，id：" + studentInfo.getWorker().getId());
            System.out.println("姓名:" + studentInfo.getWorker().getName());
            System.out.println("年龄:" + studentInfo.getWorker().getAge());
        }else{
            System.out.println("输入的类型错误...");
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello client .....^_^", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
